// 配置数据库信息
const usersql = require('../../mysql.js')
// 生成随机id
const setId = require('../../assets/id.js')
// 导入构建树形数据的函数
const treeData = require('../../assets/toTreeData.js')

// 获取平台架构
exports.getStructure = (req, res) => {
    const sql = 'select * from structure'
    usersql.query(sql, (err, results) => {
        if (err) return res.cc(err)
        if (results.length !== 0) {
            const newData = treeData(results, 0, 1)
            res.send({ status: 200, message: '获取列表成功', data: { tree: newData, total: results.length } })
        } else {
            res.cc('获取列表失败')
        }
    })
}

// 添加新分支
exports.addStructure = (req, res) => {
    // body包含name，id, pid, headid introduce
    const user = req.body
    const sql1 = 'select * from users where studentid=?'
    usersql.query(sql1, user.headid, (err, results) => {
        if (err) return res.cc(err)
        if (results.length !== 0) {
            user.head = results[0].studentname
        } else {
            return res.cc('无该学号用户')
        }
        user.id = user.id == 0 ? 0 : setId(10000000,99999999)
        user.pid= parseInt(user.pid)
        user.createtime = new Date()
        const sql2 = 'insert ignore into structure set ?'
        usersql.query(sql2, user, (err, results) => {
            if (err) return res.cc(err)
            if (results.affectedRows !== 0) {
                console.log(user)
                res.send({ status: 200, message: '添加成功', data: user })
            } else {
                
                res.cc(results)
            }
        })
    })
}

// 删除分支
exports.deleteStructure = (req, res) => {
    const id = req.query.id
    const sql = 'delete from structure where id=? or pid=?'
    // 最多删除倒数三级元素
    usersql.query(sql, [id,id], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 0) {
            res.send({ status: 200, message: '删除架构成功' })
        }
    })
}

// 修改管理员
exports.editStructureRole = (req, res) => {
    // 获取架构id
    const id = req.query.id
    // 获取提交表单headid ,name,pid introduce
    const newuser = req.body
    //得到查询的用户
    const sql = 'select * from users  where studentid=?'
    usersql.query(sql, newuser.headid, (err, results) => {
        if (err) return res.cc(err)
        if (results.length !== 0) {
            newuser.head = results[0].studentname
            const sql = 'update structure set ? where id=?'
            usersql.query(sql, [newuser, id], (err, results) => {
                if (err) return res.cc(err)
                if (results.effectRows !== 0) {
                    res.send({ status: 200, message: '编辑架构成功', data: newuser })
                } else {
                    return res.cc('编辑架构失败')
                }
            })
        } else {
            return res.cc('无该用户')
        }
    })
}